<?php

namespace teamug;

/**
 * Handles $_SESSION
 * Assumes session_start() has already been called
 * 
 */
class Session {

    private static $singleton=null;

    private function __construct() {}
    
    public static function getSingleton() {
      if (is_null(self::$singleton)) {
        self::$singleton = new Session;
      }
      return self::$singleton;
    }

  
  /**
   * Get sessions variable
   * Triggers error, and returns null if $name is not found
   * 
   * @param string $name Key name in $SESSION
   * @return mixed Value found in the session, or null if not found
   */
  public function __get($name) {
    
    if (\array_key_exists($name, $_SESSION)) {
      if (Dev::$narration) Dev::narrate("Getting \$_SESSION['$name'] - OK");
      return $_SESSION[$name];
    } else {
      \trigger_error("Failed __get(). \$_SESSION['$name'] not found in ".get_class($this), E_USER_WARNING);
      if (Dev::$narration) Dev::narrate("Getting \$_SESSION['$name'] - FAIL");
      return null;
    }
  }

  
  /**
   * Set session variable. Triggers error if variable not found
   * 
   * @param string $name Key of $_SESSION
   * @param mixed $value Value to set
   */
  public function __set($name, $value) {
    if (\array_key_exists($name, $_SESSION)) {
      $_SESSION[$name] = $value;
      if (Dev::$narration) Dev::narrate("Setting \$_SESSION['$name'] - OK");
    } else {
      \trigger_error("Failed __set() \$_SESSION['$name'] not found in ".get_class($this), E_USER_WARNING);
      if (Dev::$narration) Dev::narrate("Setting \$_SESSION['$name'] - FAIL");
    }
  }
  
  
  /**
   * Creates a session variable, providing the name does not already exist
   * 
   * @param type $name Key name for $_SESSION array
   * @param type $value Value for $_SESSION array
   */
  public function setDefault($name, $value) {
    if (Dev::$narration) Dev::narrate("Setting default session var: '$name'");
    if (!\array_key_exists($name, $_SESSION)) {
      $_SESSION[$name] = $value;
    }
  }

}
